package com.lftea.dao.impl;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.lftea.dao.IProductUnitDAO;
import com.lftea.po.ProductUnit;
import com.lftea.util.StringUtils;

@Repository("productUnitDAOImpl")
public class ProductUnitDAOImpl implements IProductUnitDAO {

	@Resource(name = "jdbcTemplate")
	private JdbcTemplate jdbcTemplate;

	public List<ProductUnit> findAll() {
		String sql = "select * from ProductUnit";
		return jdbcTemplate.query(sql, new ProductUnitMapper());
	}

	public ProductUnit findById(long productUnitId) {
		String sql = "select * from ProductUnit where ProductUnit_ID=?";
		return (ProductUnit) jdbcTemplate.query(sql,
				new Object[] { productUnitId }, new ProductUnitMapper());
	}

	public void remove(ProductUnit productUnit) {
		long productUnitId = productUnit.getId();
		String sql = "delete ProductUnit where ProductUnit_ID=?";
		jdbcTemplate.update(sql, new Object[]{productUnitId});
	}

	public void save(ProductUnit productUnit) {
		long productUnitId = productUnit.getId();
		String name = StringUtils.toISO(productUnit.getName());
		String remark = StringUtils.toISO(productUnit.getRemark());

		String sql = "select count(*) from ProductUnit where ProductUnit_ID=?";
		int result = jdbcTemplate.queryForInt(sql, new Object[]{productUnitId});
		Object[] params = null;
		if(result > 0){
			sql = "update ProductUnit set Name=?,Remark=? where ProductUnit_ID=?";
			params = new Object[]{name,remark,productUnitId};
		}else{
			sql = "insert into ProductUnit(Name,Remark) values(?,?)";
			params = new Object[]{name,remark};
		}
		jdbcTemplate.update(sql,params);
	}

	private final class ProductUnitMapper implements RowMapper<ProductUnit> {

		public ProductUnit mapRow(ResultSet rs, int rowNum) throws SQLException {
			ProductUnit productUnit = new ProductUnit();
			productUnit.setId(rs.getLong("ProductUnit_ID"));
			productUnit.setName(StringUtils.toGBK(rs.getString("name")));
			productUnit.setRemark(StringUtils.toGBK(rs.getString("remark")));
			return productUnit;
		}

	}

}
